import { RouteObject, createBrowserRouter } from "react-router-dom";
import * as React from "react";
import RouteBeforeEach from "@/components/RouteBeforeEach";

interface IRouteTable {
    path: string;
    element: React.LazyExoticComponent<any>,
    children?: IRouteTable[],
    meta?: RouteMeta;
}

const routeTable: IRouteTable[] = [
    {
        path: '/login',
        element: React.lazy(() => import('@/pages/Login')),
        meta: {
            'auth': false
        }
    },
    {
        path: '/',
        element: React.lazy(() => import('@/pages/Home')),
        meta: {
            'auth': false
        },
        children: [
            {
                path: '/',
                element: React.lazy(() => import('@/pages/Subject')),
                meta: {
                    'auth': false
                }
            },
            {
                path: '/user_info',
                element: React.lazy(() => import('@/pages/UserInfo')),
                meta: {
                    auth: true,
                }
            },
            {
                path: '/subject-info/:id',
                element: React.lazy(() => import('@/pages/SubjectInfo')),
                
            },
            {
                path: '/label-subject/:id/:type',
                element: React.lazy(() => import('@/pages/LabelSubject')),
            },
            {
                path: '/403',
                element: React.lazy(() => import('@/pages/NotRole')),
                meta: {
                    auth: false
                }
            }
        ]
    },
];

function generatorRoute(routeTable: IRouteTable[]): RouteObject[] {
    const routeObjectList: RouteObject[] = [];
    routeTable.forEach(item => {
        const routeObject = {
            path: item.path,
            element: <React.Suspense fallback="正在加载中">
                <RouteBeforeEach auth={item.meta?.auth} role={item.meta?.role}>
                    <item.element></item.element>
                </RouteBeforeEach>
            </React.Suspense>,
            children: item.children && generatorRoute(item.children),
            meta: item.meta
        }
        routeObjectList.push(routeObject);
    })
    routeObjectList.push(
        {
            path: '*',
            element: <div>404</div>
        })
    return routeObjectList;
}

export default createBrowserRouter(generatorRoute(routeTable));